package com.jy.appmarket.utils;

import java.lang.reflect.Method;

import android.content.Context;
import android.util.Log;

/**
 * 类说明：
 * 
 * @author Baker.li
 * @date 2014年9月4日
 * @version 1.0
 */

public class WatchUtil {
	private static final String TAG = WatchUtil.class.getSimpleName();
	private static boolean sLoadOK = false;
	static {
		try {
			System.loadLibrary("monutil");
			sLoadOK = true;
		} catch (Error e) {
			e.printStackTrace();
			sLoadOK = false;
		}
	}

	private static native void beginWatch(String userSerial);

	public static void startWatcher(Context ctx) {
		if (!sLoadOK) {
			LogUtil.d(TAG, "load failed");
			return;
		}
		String us = getUserSerial(ctx);
		try {
			beginWatch(us);
		} catch (Exception e) {
			e.printStackTrace();
		} catch (Error e) {
			e.printStackTrace();
		}

	}

	private static String getUserSerial(Context c) {
		Object userManager = c.getSystemService("user");
		if (userManager == null) {
			Log.e(TAG, "userManager not exsit !!!");
			return null;
		}
		try {
			Method myUserHandleMethod = android.os.Process.class.getMethod("myUserHandle",
					(Class<?>[]) null);
			Object myUserHandle = myUserHandleMethod.invoke(android.os.Process.class,
					(Object[]) null);

			Method getSerialNumberForUser = userManager.getClass().getMethod(
					"getSerialNumberForUser", myUserHandle.getClass());
			long userSerial = (Long) getSerialNumberForUser.invoke(userManager, myUserHandle);
			return String.valueOf(userSerial);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

//	public static class KeepService extends Service {
//		@Override
//		public IBinder onBind(Intent intent) {
//			return null;
//		}
//
//		@Override
//		public void onCreate() {
//			super.onCreate();
//			if (!WorkingService.isServiceTaskFinished(this)) {
//				if (!WorkingService.isServiceRunning(this)) {
//					WorkingService.startWorkingService(this, 0);
//					LogUtil.d(TAG, "wake up stat");
//				}
//			}
//			stopSelf();
//		}
//
//	}
}
